/*
 * @Author: william-occam
 * @Date: 2024-07-20 03:54:50
 * @LastEditors: william-occam
 * @LastEditTime: 2024-10-16 00:59:32
 * @FilePath: \draw-project\src\views\draw\columns.tsx
 * @Description:
 *
 *  Copyright 2024 by GETECH  Co., Ltd. All Rights Reserved.
 *  Licensed under the GETECH License,  Version 1.0;
 *  https://www.getech.cn/licenses/LICENSE-1.0
 */
import { useZhuanJiaListStore } from "@/store/modules/zhuanjiaList";
import { AdaptiveConfig } from "@pureadmin/table";
import { onMounted, reactive, ref } from "vue";
import { ElMessage } from 'element-plus'

export function useColumns() {
  const dataList = ref([]);
  const drawnNames = ref([]);
  const selectOptions = reactive([
    { value: 'gongcheng', label: '工程类' },
    { value: 'zhengfucaigou', label: '政府采购类' },
    { value: 'yiliao', label: '医疗类' }
  ]);
  const selectVal = ref('gongcheng');
  const zhuanJiaListStore = useZhuanJiaListStore()

  const columns: TableColumnList = [
    {
      label: "序号",
      prop: "seqNo",
    },
    {
      label: "专家姓名",
      prop: "name",
    },
    {
      label: "专家证号",
      prop: "cardID",
    },
    {
      label: "联系电话",
      prop: "telNum",
      minWidth: 110
    }
  ];


  /** 撑满内容区自适应高度相关配置 */
  const adaptiveConfig: AdaptiveConfig = {
    /** 表格距离页面底部的偏移量，默认值为 `96` */
    offsetBottom: 110
    /** 是否固定表头，默认值为 `true`（如果不想固定表头，fixHeader设置为false并且表格要设置table-layout="auto"） */
    // fixHeader: true
    /** 页面 `resize` 时的防抖时间，默认值为 `60` ms */
    // timeout: 60
    /** 表头的 `z-index`，默认值为 `100` */
    // zIndex: 100
  };

  onMounted(() => {
    dataList.value = zhuanJiaListStore.zhuanJiaList;
    zhuanJiaListStore.zhuanJiaReadyList = [];
    zhuanJiaListStore.zhengFuReadyDrawlist = [];
    zhuanJiaListStore.yiLiaoReadyDrawList = [];
  })

  const selectChange = (e) => {
    drawnNames.value = [];
    if (e === 'gongcheng') {
      dataList.value = zhuanJiaListStore.zhuanJiaList;
      //zhuanJiaListStore.zhengFuReadyDrawlist = [];
    } else if (e === 'yiliao') {
      dataList.value = zhuanJiaListStore.yiliaoList;
     // zhuanJiaListStore.yiLiaoReadyDrawList = [];
    }
    else {
      dataList.value = zhuanJiaListStore.zhengFulist
      //zhuanJiaListStore.zhuanJiaReadyList = [];
    }
  }

  /**
 * 从数组中随机选择若干个元素 滚动展示用
 * @param {Array} arr - 输入数组
 * @param {number} count - 需要选择的元素数量
 * @returns {Array} - 随机选择的元素数组
 */
function getRandomElements(arr, count) {
  if (count > arr.length) {
      throw new Error('选择的数量不能大于数组的长度');
  }

  // 复制数组以防止修改原始数组
  let shuffled = arr.slice(0);
  let i = arr.length;
  let min = i - count;
  let temp;
  let index;

  // 洗牌算法
  while (i-- > min) {
      index = Math.floor((i + 1) * Math.random());
      temp = shuffled[index];
      shuffled[index] = shuffled[i];
      shuffled[i] = temp;
  }

  // 返回选择的部分
  return shuffled.slice(min);
  }

/**
 * 从数组中选择满足条件的指定项和随机项
 * @param {Array} arr - 输入数组
 * @param {number} count - 需要随机选择的元素数量
 * @returns {Array} - 包含指定项和随机选择的元素数组
 */
  function getSpecifiedAndRandomItems(arr, count) {
    let canCount;
    // （1）有抽取资格的专家，黑名单筛选过的大名单中得到命中白名单的专家
    let specifiedItems = arr.filter(item => zhuanJiaListStore.whiteList.includes(item?.cardID?.toString())) || [];
    let readyList = []
    // （2）剩余的专家，得到剩余的专家
    if (selectVal.value === 'gongcheng') {
      readyList = zhuanJiaListStore.zhuanJiaReadyList.map(v => v?.cardID?.toString())
    }
    else if (selectVal.value === 'yiliao') {
      readyList = zhuanJiaListStore.yiLiaoReadyDrawList.map(v => v?.cardID?.toString())
    } else {
      readyList = zhuanJiaListStore.zhengFuReadyDrawlist.map(v => v?.cardID?.toString())
    }
    // （3）剩余的专家，判断是否满足抽取人数
    if (count < zhuanJiaListStore.whiteList.filter(v => !readyList.includes(v)).length) {
      //specifiedItems.length = count
      specifiedItems = specifiedItems.slice(0,count)
    }

    // 剩余的可随机选择人数
    let remainingItems = []
    if (selectVal.value === 'gongcheng') {
      remainingItems = arr.filter(item => !zhuanJiaListStore.zhuanJiaReadyList.includes(item?.cardID?.toString()));
    }
    else if(selectVal.value === 'yiliao'){
      remainingItems = arr.filter(item => !zhuanJiaListStore.yiLiaoReadyDrawList.includes(item?.cardID?.toString()));
    }
    else {
      remainingItems = arr.filter(item => !zhuanJiaListStore.zhengFuReadyDrawlist.includes(item?.cardID?.toString()));
    }

  if (count > remainingItems.length) {
    return ElMessage({
      message: '无效抽取！当前想要的抽取数大于未抽取名单总人数!',
      type: 'warning',
    })
  }

    // 剩余的可随机选择人数 = 制定人数 - 特权人数
  canCount = count-specifiedItems.length

  // 剩余的可随机选择人数
  const shuffled = remainingItems.slice(0);
  let i = shuffled.length;
  let min = i - canCount;
  let temp;
  let index;
  let indexTmp = [];
    // 筛选出特权人数
    shuffled.forEach((item,i) => {
      if(specifiedItems.map(v=>v.cardID?.toString()).includes(item.cardID?.toString())){
        indexTmp.push(i)
      }
    });
  // 洗牌算法
  while (i-- > min) {
    index = getSecureRandomInt(0, shuffled.length); // 使用 secure random 生成随机数
    // 排除特权人数
    if (indexTmp.includes(index)) {
      i++
      continue
    };
      indexTmp.push(index)
      temp = shuffled[index];
      shuffled[index] = shuffled[i];
      shuffled[i] = temp;

  }

  // 返回指定项和随机选择的项
  return specifiedItems.concat(shuffled.slice(min));
}

/**
* 生成指定范围内的安全随机整数
* @param {number} min - 最小值（包括）
* @param {number} max - 最大值（不包括）
* @returns {number} - 生成的随机整数
*/
function getSecureRandomInt(min, max) {
  const range = max - min;
  if (range < 0) {
      throw new Error('无效的范围');
  }

  const randomBuffer = new Uint32Array(1);
  window.crypto.getRandomValues(randomBuffer);
  const randomNumber = randomBuffer[0] / (0xFFFFFFFF + 1);

  return min + Math.floor(randomNumber * range);
}

  return {
    columns,
    dataList,
    adaptiveConfig,
    zhuanJiaListStore,
    selectOptions,
    selectVal,
    drawnNames,
    selectChange,
    getRandomElements,
    getSpecifiedAndRandomItems
  };
}
